package com.hyhy.hycloud.uaa.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hyhy.hycloud.commons.dto.InvokeResult;
import com.hyhy.hycloud.uaa.security.SecurityUser;
import com.hyhy.hycloud.uaa.service.LoginAttemptService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 登陆成功后的处理
 *
 * @author Xuegui Yuan
 * @date 2018-09-18
 */
@Slf4j
@AllArgsConstructor
public class LoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private ObjectMapper objectMapper;
    private int maxInactiveInterval;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response, Authentication authentication)
            throws IOException {

        clearAuthenticationAttributes(request);

        // 会话时间设置
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        SecurityUser securityUser = (SecurityUser) auth.getPrincipal();
        HttpSession session = request.getSession();
        if (securityUser.getMaxInactiveInterval() > 0) {
            session.setMaxInactiveInterval(securityUser.getMaxInactiveInterval());
        } else {
            session.setMaxInactiveInterval(maxInactiveInterval);
            securityUser.setMaxInactiveInterval(maxInactiveInterval);
        }
        Map<String, Object> loginTokenResult = new HashMap<>(2);
        loginTokenResult.put("token", session.getId());
        loginTokenResult.put("user", securityUser);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(objectMapper.writeValueAsString(InvokeResult.success(loginTokenResult)));
        out.flush();
        out.close();
    }
}
